<template>
  <div class="orderslist">
    <!-- 搜索框 -->
    <el-card class="searchcard">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.linkUser" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.state" placeholder="请选择状态" clearable>
            <el-option label="已支付" value="已支付" />
            <el-option label="已收货" value="已收货" />
            <el-option label="待发货" value="待发货" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="tablecard">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width:100%"
        empty-text="暂无数据"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="userId" label="下单人ID" width="100" align="center" />
        <el-table-column prop="linkUser" label="用户名" width="120" />
        <el-table-column prop="linkPhone" label="联系电话" width="150" />
        <el-table-column prop="totalPrice" label="订单金额" width="120">
          <template #default="{ row }">
            ￥{{ row.totalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="订单状态" width="100">
          <template #default="{row}">
            <el-tag :type="getOrderStatusType(row.state)">
              {{ row.state }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column prop="linkAddress" label="收货地址" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{row}">
            <el-button-group>
              <el-button type="primary"  @click="handleDetail(row)">
                详情
              </el-button>
              <el-button
                v-if="row.state === '待发货' || row.state === '已支付'"
                type="primary"
                
                @click="handleShip(row)"
              >
                发货
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5,10,15,20]"
          :total="total"
          layout="total,sizes,prev,pager,next,jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司">
            <el-option label="顺丰快递" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通快递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialogfooter">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip" :loading="shipLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="80%"
      top="5vh"
    >
      <el-table
        :data="[orderDetail]"
        border
        style="width:100%"
        empty-text="暂无数据"
      >
        <el-table-column label="图片" width="200">
          <template #default="{ row }">
            <el-image 
              :src="'http://localhost:9191' + row.img" 
              :preview-src-list="['http://localhost:9191' + row.img]"
              fit="cover"
              style="width: 150px; height: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="goodId" label="商品ID" width="100" align="center" />
        <el-table-column prop="goodName" label="商品名称" width="180" />
        <el-table-column prop="standard" label="商品规格" width="120" />
        <el-table-column prop="marketPrice" label="市价(元)" width="120" align="right">
          <template #default="{row}">
            ￥{{ (row.marketPrice || row.price / row.discount).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="折扣" width="100" align="center">
          <template #default="{row}">
            {{ (row.discount * 10).toFixed(1) }}折
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价(元)" width="120" align="right">
          <template #default="{row}">
            ￥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="数量" width="100" align="center" />
        <el-table-column label="总价(元)" width="120" align="right">
          <template #default="{row}">
            ￥{{ (row.price * row.count).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialogfooter">
          <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// import { Search,Refresh } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import request from '@/utils/request'

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(8)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  linkUser: '',
  state: ''
})

// 发货表单
const shipDialogVisible = ref(false)
const shipLoading = ref(false)
const shipFormRef = ref(null)
const currentOrderId = ref(null)
const shipForm = reactive({
  company: '',
  trackingNo: ''
})

// 订单详情
const detailDialogVisible = ref(false)
const orderDetail = ref({
  standard: '',
  img: '',
  goodName: '',
  price: 0,
  count: 0,
  discount: 1,
  goodId: ''
})

const shipRules = {
  company: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
}

// 获取订单列表
const getOrdersList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      orderNo: searchForm.orderNo,
      state: searchForm.state,
      linkUser: searchForm.linkUser
    }

    const res = await request({
      url: '/api/order/page',
      method: 'get',
      params
    })
    
    if (res.code === '200') {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败：', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取订单详情
const getOrderDetail = async (orderNo) => {
  try {
    const res = await request({
      url: `/api/order/orderNo/${orderNo}`,
      method: 'get'
    })
    
    if (res.code === '200') {
      orderDetail.value = res.data || {}
      detailDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败：', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 查看详情
const handleDetail = (row) => {
  getOrderDetail(row.orderNo)
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getOrdersList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 发货
const handleShip = (row) => {
  currentOrderId.value = row.id
  shipForm.company = ''
  shipForm.trackingNo = ''
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = async () => {
  try {
    await shipFormRef.value.validate()
    shipLoading.value = true
    
    const res = await request({
      url: `/order/ship/${currentOrderId.value}`,
      method: 'put',
      data: shipForm
    })
    
    if (res.code === '200') {
      ElMessage.success('发货成功')
      shipDialogVisible.value = false
      getOrdersList()
    } else {
      ElMessage.error(res.msg || '发货失败')
    }
  } catch (error) {
    console.error('发货失败', error)
    if (error !== 'validate') {
      ElMessage.error('发货失败，请稍后重试')
    }
  } finally {
    shipLoading.value = false
  }
}

// 获取订单状态类型
const getOrderStatusType = (state) => {
  const types = {
    '已支付': 'warning',
    '待发货': 'primary',
    '已发货': 'success',
    '已收货': 'success',
    '已完成': 'success',
    '已取消': 'info'
  }
  return types[state] || 'info'
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getOrdersList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getOrdersList()
}

onMounted(() => {
  getOrdersList()
})
</script>

<style scoped>
.searchcard {
  margin-bottom: 20px;
}
.search-form {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>